import type { AxiosResponse } from 'axios'
import type { ILoginParams } from '@/types/api/user.js'
import type { IRouteMenuRecordRaw } from '@/types/pinia/user.js'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { userLoginAPI } from '@/api/user.js'
import { routes } from '@/router/routes.js'

const useUserStore = defineStore('user', {
  state: () => {
    return {
      menu: [] as IRouteMenuRecordRaw[],
    }
  },
  actions: {
    /**
     * 用户登录验证
     * @param loginParams 登录账号信息
     * @returns undefined ||  res.data   验证成功返回请求响应数据（包含accesst_tooken)，失败返回undefined
     */
    async userLogin(loginParams: ILoginParams) {
      const res = await userLoginAPI(loginParams).catch(err => err) as AxiosResponse
      if (!res.success) {
        ElMessage.error(res.message || '失败')
        return void 0
      }
      this.setMeun()
      return res.data
    },

    setMeun(menu: IRouteMenuRecordRaw[] = []) {
      menu.unshift(...routes)
      this.menu = menu
    },
  },
})

export default useUserStore
